package com.itheima.service.impl;

import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加套餐
     *
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    @Transactional
    public void add(String[] checkgroupIds, Setmeal setmeal) {
        //添加套餐表信息
        setmealMapper.addSetmeal(setmeal);

        //添加 套餐-检查组 关联表信息
        Integer setmealId = setmeal.getId();
        setmealMapper.addSetmealWithCheckGroup(setmealId, checkgroupIds);
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        Integer start = (currentPage - 1) * pageSize;

        //查询总记录数
        Long total = setmealMapper.selectTotal();
        //查询当前页数据
        List<Setmeal> rows = setmealMapper.selectPage(start, pageSize, queryString);
        return new PageResult(total, rows);
    }

    /**
     * 根据套餐id查询套餐信息
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(String id) {
        Setmeal setmeal = setmealMapper.findById(id);
        return setmeal;
    }

    /**
     * 编辑套餐
     * @param checkGroupIds
     * @param setmeal
     */
    @Override
    @Transactional
    public void edit(String[] checkGroupIds, Setmeal setmeal) {
        //更新套餐信息
        setmealMapper.update(setmeal);

        //更新套餐和检查组关联信息
        //1.先删除套餐和检查组关联信息
        setmealMapper.delSetmealWithCheckGroup(setmeal.getId());
        //2.添加套餐和检查组关联信息
        setmealMapper.addSetmealWithCheckGroup(setmeal.getId(), checkGroupIds);
    }
}
